
class Dashboard::InvoicesController < Dashboard::BaseController
  before_action :require_logined
  before_action :find_invoice, only: [:edit, :update, :destroy, :set_default_invoice]

  def index
    @invoices = current_user.invoices
    @default = current_user.invoices.find_by(is_default: true)
    @orders = current_user.orders.paginate(page: params[:page] || 1, per_page: 10)

    respond_to do |format|
      format.html
      format.json do
        render json: {
          status: 'ok',
          invoices: @invoices,
          defaultId: @default ? @default.id : nil
        }
      end
    end
  end

  def new
    @invoice = current_user.invoices.new
    @order = current_user.orders.find(params[:order_id])
  end

  def create
    current_invoices = current_user.invoices
    invoice = current_invoices.new(invoice_params)
    if current_invoices.count <= 5 && invoice.save
      @invoices = current_user.reload.invoices
      render json: {
        status: 'ok',
        invoices: @invoices,
        defaultId: invoice.id
      }
    else
      render json: {
        status: 'error',
        msg: '添加错误，请重新添加'
      }
    end
  end

  def edit
    render action: :new
  end

  def update
    @invoice.attributes = invoice_params
    if @invoice.save
      render_success('更新开票信息成功')
    else
      render_fail('更新开票信息失败')
    end
  end

  def destroy
    @invoice.destroy!
    @invoices = current_user.invoices
    render json: {
      status: 'ok',
      invoices: @invoices
    }
  rescue
    render json: {
      status: 'error',
      msg: '删除错误，请重新添加'
    }
  end

  def set_default_invoice
    @invoices = current_user.invoices
    @invoices.update_all(is_default: false)
    @invoice.is_default = true
    if @invoice.save
      # render_success("设置默认发票成功")
      render json: {
        status: 'ok',
        invoices: @invoices,
        defaultId: @invoice.id
      }
    else
      render json: {
        status: 'error',
        msg: '设置失败，请重试'
      }
    end
  end

  def make_invoice
    order = Order.find params[:order_id]
    order.invoice_id = params[:invoice_id]
    if order.save
      flash[:notice] = "开票成功"
    else
      flash[:notice] = "开票失败"
    end
    redirect_to :back
  end

  private

  def invoice_params
    params.require(:invoice).permit!
  end

  def find_invoice
    @invoice = current_user.invoices.find(params[:id])
  end
end
